﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Crawler.DataAccess
{
    public class RavenDbProvider : IDataProvider
    {
        public string ConnectionString { get; set; }

        public RavenDbProvider()
        {
        }

        public void InsertModel(object model)
        {
            using (RavenDBDocumentRepository rep = new RavenDBDocumentRepository(ConnectionString))
            {
                rep.Store(model);
                rep.SaveChanges();
            }
        }

        public void DeleteModel(string metadata, object filter)
        {
            using (RavenDBDocumentRepository rep = new RavenDBDocumentRepository(ConnectionString))
            {
                rep.Delete(filter);
                rep.SaveChanges();
            }
        }

        public object LoadModel(string metadataName, object modelFilter)
        {
            using (RavenDBDocumentRepository rep = new RavenDBDocumentRepository(ConnectionString))
            {
                return rep.Load<object>(modelFilter.ToString());
            }
        }

        public List<T> LoadAllModels<T>(string metadataName)
        {
            using (RavenDBDocumentRepository rep = new RavenDBDocumentRepository(ConnectionString))
            {
                return rep.Query<T>().ToList();
            }
        }

        public List<T> LoadAllModels<T>(string metadataName, object modelFilter)
        {
            using (RavenDBDocumentRepository rep = new RavenDBDocumentRepository(ConnectionString))
            {
                return rep.Query<T>().ToList();
            }
        }

        public List<T> LoadAllModels<T>(string metadataName, object modelFilter, int topN)
        {
            using (RavenDBDocumentRepository rep = new RavenDBDocumentRepository(ConnectionString))
            {
                return rep.Query<T>().Take(topN).ToList();
            }
        }

        public List<T> LoadAllModels<T>(string metadataName, object modelFilter, int startIndex, int count)
        {
            using (RavenDBDocumentRepository rep = new RavenDBDocumentRepository(ConnectionString))
            {
                return rep.Query<T>().Skip(startIndex).Take(count).ToList();
            }
        }

        public void UpdateModel(string metadata, object model)
        {
            using (RavenDBDocumentRepository rep = new RavenDBDocumentRepository(ConnectionString))
            {
                rep.Store(model);
                rep.SaveChanges();
            }
        }

        public Dictionary<string, object> LoadColumns(string metadataName, object modelFilter, params string[] columns)
        {
            throw new NotImplementedException();
        }
    }
}